package com.raising.utils;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class HttpUtils {

    /**
     * 获取method （大写）
     * @author GaoYuan
     * @date 2018/5/8 上午11:19
     */
    public static String getRequestMethod(HttpServletRequest request) {
        String sMethod = request.getMethod();
        return sMethod.toUpperCase();
    }

    /**
     * 获取参数
     * @author GaoYuan
     * @date 2018/5/30 上午8:41
     */
    public static Map<String,String> getParams(HttpServletRequest request){
        TreeMap<String, String> values = new TreeMap<String, String>();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String name =(String) paramNames.nextElement();
            String value = request.getParameter(name);
            values.put(name, value);
        }
        return values;
    }

    /**
     * 获取参数
     * @author GaoYuan
     * @date 2018/5/30 上午8:41
     */
    public static String getParamsChar(HttpServletRequest request){
        String params = "";
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String name = (String) paramNames.nextElement();
            String value = request.getParameter(name);
            params += "&" + name + "=" + value;
        }
        return params;
    }


    /**
     * 获取所有请求头
     * @author GaoYuan
     * @date 2018/5/25 下午3:13
     */
    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>(16);
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
    /**
     * 获取请求头 - 字符串拼接格式
     * @author GaoYuan
     * @date 2018/5/25 下午3:16
     */
    public static String getHeadersChar(HttpServletRequest request) {
        String headers = "";
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            headers += key + "=" + value + "\r\n";
        }
        return headers;
    }

    /**
     * 二进制读取
     * @author GaoYuan
     * @date 2018/5/25 上午11:30
     */
    public static InputStream getRequestBody(HttpServletRequest request) {
        InputStream requestEntity = null;
        try {
            requestEntity = request.getInputStream();
        }
        catch (IOException ex) {
        }
        return requestEntity;
    }
    /**
     * 字符串读取
     * @author GaoYuan
     * @date 2018/5/25 上午11:30
     */
    public static String getRequestBodyChar(HttpServletRequest request) {
        try {
            BufferedReader br = request.getReader();
            String str, wholeStr = "";
            while((str = br.readLine()) != null){
                wholeStr += str;
            }
            return wholeStr;
        }catch (Exception e){

        }
        return "";
    }


    /**
     * 如果nginx代理，则默认情况下不会获取真实的请求ip地址
     * 利用 X-Real-IP
     *  需要修改 nginx.conf 配置文件
     *  location /{
     *      proxy_set_header X-Real-IP    $remote_addr;
     *      ...
     *  }
     */
    public static String getIpAddress(HttpServletRequest request){
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }
}
